package main

import (
	"code.google.com/p/goblinite/lib"
	"errors"
	"flag"
	"fmt"
	"io"
	"os"
)

const command = "cp"

func usage() {
	fmt.Fprint(os.Stderr, "usage: ", command, " [-gux] fromfile tofile\n")
	os.Exit(2)
}

// todo: check if src+dst are the same file (os.SameFile())
// todo: check permissions
// TODO: implement this
func main() {
	// -r: recursively
	flag.Usage = usage
	flag.Parse()
	if flag.NArg() < 2 {
		usage()
	}
	lastArg := flag.Arg(flag.NArg() - 1)
	if flag.NArg() > 2 {
		// more than 2 arguments -> last argument has to be a directory
		if info, err := os.Stat(lastArg); err != nil {
			if os.IsNotExist(err) {
				lib.Fatal(command, errors.New(lastArg+" is not a directory"))
			}
		} else {
			if !info.IsDir() {
				lib.Fatal(command, errors.New(lastArg+" is not a directory"))
			}
		}
		os.Exit(0)
	}
	var src, dst *os.File
	var err error
	for i := 0; i < flag.NArg()-1; i++ {
		if src, err = os.Open(flag.Arg(i)); err != nil {
			lib.Fatal(command, err)
		}
		if dst, err = os.Create(lastArg); err != nil {
			src.Close()
			lib.Fatal(command, err)
		}
		// todo: which permissions? 0666 is default
		if _, err := io.Copy(dst, src); err != nil {
			src.Close()
			dst.Close()
			lib.Fatal(command, err)
		}
	}

}
